//
//  BaseViewController.m
//  O2O-AccountManager
//
//  Created by 李良 on 16/1/28.
//  Copyright © 2016年 liliang. All rights reserved.
//

#import "DLBaseViewController.h"
#import "DLBaseNavigationController.h"
#import "UIView+Extension.h"
#import "DLTableBgView.h"
#import "DLRefreshHeader.h"
#import "DLRefreshFooter.h"
#import <DGGCommonSDK/DLThemeAdapter.h>
#import <MJRefresh/MJRefresh.h>

static NSString * const countKey = @"countKey";
static NSString * const startIndexKey = @"startIndexKey";
static NSString * const dataArrayKey = @"dataArrayKey";
static NSString * const isLoadingKey = @"isLoadingKey";
static NSString * const errorKey = @"errorKey";
static NSString * const isDggTabStatusCustomKey = @"isDggTabStatusCustom";
static NSString * const dggTabStatus_NoneKey = @"dggTabStatus_None";
static NSString * const dggTabStatus_CustomKey = @"dggTabStatus_CustomKey";
static NSString * const dggTabStatus_ErrorDictKey = @"dggTabStatus_ErrorDict";
static NSString * const dggTabStatusClickKey = @"dggTabStatusClickKey";
static NSString * const bGCenterYKey = @"bGCenterYKey";
@interface DLBaseViewController ()

@property (nonatomic,copy)NSString *tableNameKey;
@end

@implementation DLBaseViewController
@synthesize dggTabStatus_ErrorDict = _dggTabStatus_ErrorDict;
@synthesize dggTabStatus_CustomDict = _dggTabStatus_CustomDict;
@synthesize dggTabStatus_NoneDict = _dggTabStatus_NoneDict;
@synthesize dggTabStatusClick = _dggTabStatusClick;
@synthesize dataArray = _dataArray;
@synthesize noDataText = _noDataText;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    
    DLBaseViewController *viewController = [super allocWithZone:zone];
    
    @weakify(viewController)
    
    [[viewController rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x) {
        
        @strongify(viewController)
         [viewController dgg_addSubviews];
         [viewController dgg_addNavItems];
         [viewController dgg_bindTableView];
        [viewController dgg_setTableView];
        [viewController dgg_refreshControls];
        if (![NSString isEmpty:viewController.tableNameKey]) {
            UITableView *tableView =[viewController valueForKey:viewController.tableNameKey];
            if (tableView.mj_header) {
                [tableView.mj_header beginRefreshing];
            }else
            {
                [viewController dgg_requestData];
            }
        }else
        {
            [viewController dgg_requestData];
        }
    }];
    [[viewController rac_signalForSelector:@selector(viewWillAppear:)] subscribeNext:^(id x) {
        
        @strongify(viewController)
        [viewController dgg_layoutNavigation];
        [viewController dgg_requestNewData];
    }];
    [[viewController rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x) {
        
        @strongify(viewController)
        [viewController dgg_recoverKeyboard];

    }];
        unsigned int index;
        BOOL isNumberOfSections = NO;
        BOOL isNumberOfRows = NO;
        Method *methods = class_copyMethodList([viewController class], &index);
        for (int i = 0; i < index; i++)
        {
            Method method = methods[i];
            SEL selector = method_getName(method);
            NSString *name = NSStringFromSelector(selector);
            
            
            if([name rangeOfString:@"numberOfSectionsInTableView:"].location !=NSNotFound)
            {
                isNumberOfSections = YES;
            }
            if([name rangeOfString:@"tableView:numberOfRowsInSection:"].location !=NSNotFound)
            {
                isNumberOfRows = YES;
            }
            
        }
    
    if (isNumberOfSections) {
        [[[viewController rac_signalForSelector:@selector(numberOfSectionsInTableView:)] delay:0.2] subscribeNext:^(id x) {
            
            @strongify(viewController)
            if (![NSString isEmpty:viewController.tableNameKey]) {
                UITableView *tableView =[viewController valueForKey:viewController.tableNameKey];
                NSNumber * isLoading = objc_getAssociatedObject(viewController, &isLoadingKey);
                if (tableView&&isLoading!=nil) {
                    [viewController addBackgroundView];
                }
            }
        }];
    }else if (isNumberOfRows){
        [[[viewController rac_signalForSelector:@selector(tableView:numberOfRowsInSection:)] delay:0.2] subscribeNext:^(id x) {
            
            @strongify(viewController)
            if (![NSString isEmpty:viewController.tableNameKey]) {
                UITableView *tableView =[viewController valueForKey:viewController.tableNameKey];
                NSNumber * isLoading = objc_getAssociatedObject(viewController, &isLoadingKey);
                if (tableView&&isLoading!=nil) {
                    [viewController addBackgroundView];
                }
            }
        }];
    }
    return viewController;
}
    
-(void)viewDidLoad
{
    [super viewDidLoad];
    [self dgg_setNav];
}
    
- (void)dgg_setNav
{
    if (self.navigationController) {
        if ([self.navigationController isKindOfClass:[DLBaseNavigationController class]]) {
//            DLBaseNavigationController *nav = (DLBaseNavigationController*)self.navigationController;
        }
    }
}
    
- (void)dealloc {
    
    NSLog(@"♦️释放♦️ %@ '%@'", NSStringFromSelector(_cmd), self.class);
}
    
/**
 添加下拉 手动调用
 */
- (void)dgg_addRefreshHeader
{
    
    if ([NSString isEmpty:self.tableNameKey]) {
        NSLog(@"tableView未绑定成功 无法添加下拉刷新");
        return;
    }
     UITableView *tableView =[self valueForKey:self.tableNameKey];
    kself
   tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.startIndex = 1;
        [weakSelf dgg_requestData];
    }];
  
    
}
    
/**
 添加上啦 手动调用
 */
- (void)dgg_addRefreshFooter
{
    if ([NSString isEmpty:self.tableNameKey]) {
        NSLog(@"tableView未绑定成功 无法添加下拉刷新");
        return;
    }
    UITableView *tableView =[self valueForKey:self.tableNameKey];
    
     kself
   tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.startIndex +=1;
        [weakSelf dgg_requestData];
    }];
   tableView.mj_footer.automaticallyHidden = YES;
}
    
/**
 添加上啦下拉
 */
- (void)dgg_refreshControls{}
    
/**
 设置tableView
 */
-(void)dgg_setTableView{}
    
/**
 添加UI 设置UI
 */
- (void)dgg_addSubviews{}

/**
 设置导航 本方法每次在viewWillAppear会调用
 */
- (void)dgg_layoutNavigation{}

/**
 数据请求 本方法每次在viewWillAppear会调用
 */
- (void)dgg_requestNewData{}

/**
 数据请求 本方法在viewDidLoad会调用
 */
- (void)dgg_requestData{}
    
/**
 添加导航item
 */
- (void)dgg_addNavItems
{
    
}

/**
 隐藏键盘
 */
- (void)dgg_recoverKeyboard
{
    [self.view endEditing:YES];
}
/**
 
 绑定tableView 不要重写此方法
 方法在viewDidLoad 调用  如果viewDidLoad没有创建tableView  则在tableView创建后调用
 
 */
-(void)dgg_bindTableView
{
    unsigned  int count = 0;
    Ivar *members = class_copyIvarList([self class], &count);
    
    
    NSString *keyName = @"";
    NSInteger c = 0 ;
    for (int i = 0; i < count; i++)
    {
        Ivar var = members[i];
       NSString * key = [NSString stringWithUTF8String:ivar_getName(var)];
       NSString * type = [NSString stringWithUTF8String:ivar_getTypeEncoding(var)];
       
        if ([type isEqualToString:@"@\"UITableView\""]) {
            c += 1;
            keyName = key;
        }
    }
    
    
    if (c <=1) {
         self.tableNameKey = keyName;
        
        if (![NSString isEmpty:self.tableNameKey]) {
            UITableView *tableView =[self valueForKey:self.tableNameKey];
                if (@available(iOS 11.0, *)) {
                    tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
                }else {
                    self.automaticallyAdjustsScrollViewInsets = NO;
                }
        }
    }else
    {
        NSLog(@"多个tableView 未绑定");
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"内存警告");
}

-(void)addBackgroundView
{
    NSDictionary * dict = [self tableBackgroundViewDict];
    if (dict) {
        kself
        NSInteger tag = 0;
        if (dict == self.dggTabStatus_NoneDict)
        {
            tag = DGGTabStatus_None+10;
        }else if (dict == self.dggTabStatus_ErrorDict)
        {
            tag = DGGTabStatus_Error+10;
        }
        UITableView *tableView =[self valueForKey:self.tableNameKey];
        if (tableView.backgroundView .tag == tag &&tag!=0) {
            //不做重复添加
            return;
        }
        
        __weak typeof (tableView) weakTable = tableView;
        tableView.backgroundView = [DLTableBgView loadNibWithImageName:dict[kDLTabStatus_imageKey]
                                                                 title:dict[kDLTabStatus_titleKey]
                                                             isShowBtn:[dict[kDLTabStatus_isShowBtnKey] boolValue]
                                                              btnTitle:dict[kDLTabStatus_btnTitleKey]
                                                               content:dict[kDLTabStatus_contentKey]
                                                               centerY:self.bGViewCenterY
                                                           buttonColor:self.navigationController.navigationBar.barTintColor block:^{
            weakSelf.isLoading = NO;
            weakSelf.error = NO;
            [weakTable reloadData];
            if (weakTable.mj_header) {
                [weakTable.mj_header beginRefreshing];
            }else
            {
                NSLog(@"没有mj_header  请使用self.dggTabStatusClick 监听按钮回调");
            }
            
            if (dict == weakSelf.dggTabStatus_CustomDict) {
                [weakSelf.dggTabStatusClick sendNext:@(DGGTabStatus_Custom)];
            }else if (dict == weakSelf.dggTabStatus_NoneDict)
            {
                [weakSelf.dggTabStatusClick sendNext:@(DGGTabStatus_None)];
            }else if (dict == weakSelf.dggTabStatus_ErrorDict)
            {
                [weakSelf.dggTabStatusClick sendNext:@(DGGTabStatus_Error)];
            }
            
        }];
         tableView.backgroundView.tag = tag;
    }else
    {
        UITableView *tableView =[self valueForKey:self.tableNameKey];
        tableView.backgroundView = nil;
    }
}

-(NSDictionary *)tableBackgroundViewDict
{
    UITableView *tableView =[self valueForKey:self.tableNameKey];
    CGFloat height = tableView.sectionHeaderHeight + tableView.sectionFooterHeight;
    if (height <0) {
        height = 0 ;
    }
    if (tableView.tableHeaderView) {
        height += tableView.tableHeaderView.height;
        
    }
    if (tableView.tableFooterView) {
        height += tableView.tableFooterView.height;
        
    }
    for (NSInteger section = 0; section<tableView.numberOfSections; section++) {
        if ([self respondsToSelector:@selector(tableView:heightForHeaderInSection:)]) {
          
            height += [self tableView:tableView heightForHeaderInSection:section];
        }
        if ([self respondsToSelector:@selector(tableView:heightForFooterInSection:)]) {
            height += [self tableView:tableView heightForFooterInSection:section];
        }
    }
    if (tableView.contentSize.height-height<=5 &&self.isLoading&&!self.error&&self.isDggTabStatusCustom) {
        
        return self.dggTabStatus_CustomDict;
    }else if (tableView.contentSize.height-height<=5  &&self.isLoading&&!self.error&&!self.isDggTabStatusCustom) {
        
        return self.dggTabStatus_NoneDict;
    }
    else if (tableView.contentSize.height-height<=5  &&self.isLoading&&self.error) {
        
        return self.dggTabStatus_ErrorDict;
    }else
    {
        return nil;
    }
    
}
    
-(NSInteger)count
{
    NSNumber * count = objc_getAssociatedObject(self, &countKey);
    if (! count)
    {
        objc_setAssociatedObject(self, &countKey, @(kCount), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        count = objc_getAssociatedObject(self, &countKey);
    }
        return [count integerValue];
}
    
-(void)setCount:(NSInteger)count
{
    objc_setAssociatedObject(self, &countKey, @(count), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
    
-(NSInteger)startIndex
{
    NSNumber * startIndex = objc_getAssociatedObject(self, &startIndexKey);
    if (! startIndex)
    {
        objc_setAssociatedObject(self, &startIndexKey, @(kStartIndex), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
       startIndex = objc_getAssociatedObject(self, &startIndexKey);
    }
    
    return [startIndex integerValue];
    
}
    
-(void)setStartIndex:(NSInteger)startIndex
{
    objc_setAssociatedObject(self, &startIndexKey, @(startIndex), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
    
-(NSMutableArray*)dataArray
{
   NSMutableArray *array =  objc_getAssociatedObject(self, &dataArrayKey);
    if (!array) {
        objc_setAssociatedObject(self, &dataArrayKey, @[].mutableCopy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        array =  objc_getAssociatedObject(self, &dataArrayKey);
        
    }
    return array;
    
}
    
-(void)setDataArray:(NSMutableArray *)dataArray
{
    objc_setAssociatedObject(self, &dataArrayKey, dataArray, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(BOOL)isLoading
{
    NSNumber * isLoading = objc_getAssociatedObject(self, &isLoadingKey);
    if (!isLoading) {
        objc_setAssociatedObject(self, &isLoadingKey, @(NO), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        isLoading = objc_getAssociatedObject(self, &isLoadingKey);
    }
        return [isLoading boolValue];
}
    
-(void)setIsLoading:(BOOL)isLoading
{
    if (isLoading) {
        objc_setAssociatedObject(self, &errorKey, @(NO), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    objc_setAssociatedObject(self, &isLoadingKey, @(isLoading), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
    
-(BOOL)error
{
    NSNumber * error = objc_getAssociatedObject(self, &errorKey);
    if (!error) {
        objc_setAssociatedObject(self, &errorKey, @(NO), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        error = objc_getAssociatedObject(self, &errorKey);
    }
    return [error boolValue];
}
    
-(void)setError:(BOOL)error
{
    objc_setAssociatedObject(self, &errorKey, @(error), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)setNoDataText:(NSString *)noDataText
{
    _noDataText = noDataText;
    objc_setAssociatedObject(self, &dggTabStatus_NoneKey,  @{kDLTabStatus_contentKey:kFormat(noDataText).isEmpty,kDLTabStatus_imageKey:kDLTabStatus_None_image,kDLTabStatus_isShowBtnKey:@(kDLTabStatus_None_isShowBtn),kDLTabStatus_btnTitleKey:kDLTabStatus_None_btnTitle,kDLTabStatus_titleKey:kDLTabStatus_None_title}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(BOOL)isDggTabStatusCustom
{
    NSNumber * isDggTabStatusCustom = objc_getAssociatedObject(self, &isDggTabStatusCustomKey);
    if (!isDggTabStatusCustom) {
         objc_setAssociatedObject(self, &isDggTabStatusCustomKey, @(NO), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        isDggTabStatusCustom = objc_getAssociatedObject(self, &isDggTabStatusCustomKey);
        
    }
        return [isDggTabStatusCustom boolValue];
}
    
-(void)setIsDggTabStatusCustom:(BOOL)isDggTabStatusCustom
{
    objc_setAssociatedObject(self, &isDggTabStatusCustomKey, @(isDggTabStatusCustom), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
    
- (CGFloat)bGViewCenterY
{
    NSNumber * bGViewCenterY = objc_getAssociatedObject(self, &bGCenterYKey);
    if (!bGViewCenterY) {
        objc_setAssociatedObject(self, &bGCenterYKey, @(0), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        bGViewCenterY = objc_getAssociatedObject(self, &bGCenterYKey);
        
    }
    return [bGViewCenterY floatValue];
}
    
- (void)setBGViewCenterY:(CGFloat)bGViewCenterY
{
    objc_setAssociatedObject(self, &bGCenterYKey, @(bGViewCenterY), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
    
-(NSDictionary*)dggTabStatus_NoneDict
{
    NSDictionary *dict =  objc_getAssociatedObject(self, &dggTabStatus_NoneKey);
    
    if (!dict) {
        objc_setAssociatedObject(self, &dggTabStatus_NoneKey,  @{kDLTabStatus_contentKey:kDLTabStatus_None_content,kDLTabStatus_imageKey:kDLTabStatus_None_image,kDLTabStatus_isShowBtnKey:@(kDLTabStatus_None_isShowBtn),kDLTabStatus_btnTitleKey:kDLTabStatus_None_btnTitle,kDLTabStatus_titleKey:kDLTabStatus_None_title}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        dict =  objc_getAssociatedObject(self, &dggTabStatus_NoneKey);
    }
    
    return dict;
}
    
-(void)setDggTabStatus_NoneDict:(NSDictionary *)dggTabStatus_NoneDict
{
    objc_setAssociatedObject(self, &dggTabStatus_NoneKey, dggTabStatus_NoneDict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSMutableDictionary*)dggTabStatus_CustomDict
{
    
    NSMutableDictionary *dict = objc_getAssociatedObject(self, &dggTabStatus_CustomKey);
    if (!dict) {
          objc_setAssociatedObject(self, &dggTabStatus_CustomKey, @{kDLTabStatus_contentKey:kDLTabStatus_Custom_content,kDLTabStatus_imageKey:kDLTabStatus_Custom_image,kDLTabStatus_isShowBtnKey:@(kDLTabStatus_Custom_isShowBtn),kDLTabStatus_btnTitleKey:kDLTabStatus_Custom_btnTitle,kDLTabStatus_titleKey:kDLTabStatus_None_title}.mutableCopy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        dict = objc_getAssociatedObject(self, &dggTabStatus_CustomKey);
     
    }
    return dict;
}
    
-(void)setDggTabStatus_CustomDict:(NSMutableDictionary *)dggTabStatus_CustomDict
{
    objc_setAssociatedObject(self, &dggTabStatus_CustomKey, dggTabStatus_CustomDict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSDictionary*)dggTabStatus_ErrorDict {
    
    NSDictionary *dict = objc_getAssociatedObject(self, &dggTabStatus_ErrorDictKey);
    if (!dict) {
        objc_setAssociatedObject(self, &dggTabStatus_ErrorDictKey, @{kDLTabStatus_contentKey:kDLTabStatus_Error_content,kDLTabStatus_imageKey:kDLTabStatus_Error_image,kDLTabStatus_isShowBtnKey:@(kDLTabStatus_Error_isShowBtn),kDLTabStatus_btnTitleKey:kDLTabStatus_Error_btnTitle,kDLTabStatus_titleKey:kDLTabStatus_Error_title}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        dict = objc_getAssociatedObject(self, &dggTabStatus_ErrorDictKey);
        
    }
    return dict;
    
    
    
}
    
-(void)setDggTabStatus_ErrorDict:(NSDictionary *)dggTabStatus_ErrorDict
{
    objc_setAssociatedObject(self, &dggTabStatus_ErrorDictKey, dggTabStatus_ErrorDict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(RACSubject*)dggTabStatusClick
{
    RACSubject *rac = objc_getAssociatedObject(self, &dggTabStatusClickKey);
    if (!rac) {
        objc_setAssociatedObject(self, &dggTabStatusClickKey,  [RACSubject subject], OBJC_ASSOCIATION_RETAIN_NONATOMIC);

        rac = objc_getAssociatedObject(self, &dggTabStatusClickKey);
    }
    return rac;
}
    
-(void)setDggTabStatusClick:(RACSubject *)dggTabStatusClick
{
    objc_setAssociatedObject(self, &dggTabStatusClickKey, dggTabStatusClick, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

#pragma mark - 下拉刷新&上拉加载

- (void)addPullDownRefreshForTableView:(UIScrollView *)tableview tintColor:(UIColor *)tintColor  completionRefreshBlock:(MJRefreshComponentRefreshingBlock)componentRefreshingBlock{
    DLRefreshHeader *refreshHeader = [DLRefreshHeader headerWithRefreshingBlock:componentRefreshingBlock];
    refreshHeader.tintColor = tintColor;
    refreshHeader.isShowTextAndCircleView = NO;
    [refreshHeader show];
    tableview.mj_header = refreshHeader;
}

- (void)addPullUpLoadMoreDataForTableView:(UIScrollView *)tableview tintColor:(UIColor *)tintColor noDataText:(NSString *)noDataText
                   completionRefreshBlock:(MJRefreshComponentRefreshingBlock)componentRefreshingBlock{

    DLRefreshFooter *refreshFooter = [DLRefreshFooter footerWithRefreshingBlock:componentRefreshingBlock];
    refreshFooter.noDataStr = noDataText ? noDataText : @"没有更多数据";
    refreshFooter.isShowTextAndCircleView = NO;
    refreshFooter.tintColor = tintColor;
    tableview.mj_footer = refreshFooter;
    
}

- (void)endRefreshingComponentForTableView:(UIScrollView *)tableView {
    [tableView.mj_header endRefreshing];
    [tableView.mj_footer endRefreshing];
}

#pragma mark - 屏幕方向切换
//是否可以旋转
- (BOOL)shouldAutorotate
{
    return NO;
}

//支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

@end
